#!/bin/sh
temp_file="/tmp/MiniCD.tmp"
title_file="title.cdb"
track_file="track.cdb"

set_menu_choice() {
	echo menu...please select your option:
	echo "		a) Add new CD."
	echo "		f) find CD."
	echo "		c) Count the CDs and tracks in the catalog."

	if [ "$cdcatnum" != "" ]; then
		echo "		l) List tracks on $cdtitle"
		echo "		r) Remove $cdtitle"
		echo "		u) Update track information for $cdtitle"
	fi	

	echo "		q) Quit."
	echo
	read menu_choice
	return
}

get_confirm() {
	echo -e "Are you sure? \c"
	while true
	do 
	read answer
		case "$answer" in 
		[yY][eE][sS]) return 1;;
		[nN]*[oO] return 0;
	esac
	done
		
}

trap 'rm $temp_file' INT 

insert_title() {
	echo "$@" >> $title_file 
}

insert_track() {
	echo "$@" >> $track_file
}


add_cd_tracks() {
	cd_track=1
	echo "now enter information for this record."
	echo "when you no more want to enter, enter q to exit."
	while [ "$music_name" != "q" ]
	do
		echo -e "Track $cd_track, track title? \c"
		read tmp
		music_name=$ {tmp%%,*}

		if [ "$tmp" != "$music_name"]; then
			echo "no commas allowed."
			continue
		fi

		if [-n "$music_name"]; then
			insert_track $cd_catalog_name,$cd_track,$music_name
		fi
	done
}

find_cd() {
	if [ "$1" = "n" ]; then
		ask_list="n"
	else
		ask_list="y"
	fi

	cd_catalog_name=""
	echo -e "please enter the cd you want: \c"
	read cd_find_title
	while [-z "$cd_find_title"]; do
		echo -e "null input is invalid, please enter the cd you want: \c"
	done

	
}
remove_cd() {
	if [ -z "$cd_catalog_name" ]; then
		echo "you must select a CD first."
		find_cd n
	fi

	if [ -n "$cd_catalog_name" ]; then
		echo "you are about to delete $cd_title"
	
		get_confirm && {
			grep -v "^$cd_catalog_name" $title_file > $temp_file
			mv $temp_file $title_file
			grep -v "^$cd_catalog_name" $track_file > $temp_file
			mv $temp_file $track_file
			cd_catalog_name=""
			echo "$cd_title has been removed."
		}
	fi

}
add_cd() {
	#这些变量用全局的还是局部的？
	echo -e "please enter cd catalog name:		\c"
	read cd_catalog_name
	echo -e "please enter cd title:		\c"
	read cd_title
	echo -e "please enter cd type:		\c"
	read cd_type
	echo -e "please enter cd composer/artist:		\c"
	read cd_artist

	get_confirm && {
		insert_title $cd_catalog_name,$cd_title,$cd_type,$cd_artist
		add_cd_tracks
	}

	cd_catalog_name=""
	cd_title=""
	cd_type=""
	cd_artist=""

	return
}

set_menu_choice

